package cn.ffcs.uec.outStaff.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.outStaff.component.bean.UecOutStaffFamilyListboxBean;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.staff.manager.UecFamilyManager;
import cn.ffcs.uec.staff.manager.UecTrialManager;
import cn.ffcs.uec.staff.model.UecFamily;
import cn.ffcs.uec.staff.model.UecTrial;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.PageInfo;
import cn.ffcs.uom.common.zul.PubUtil;
import lombok.Getter;
import lombok.Setter;

/**
 * @Title:外包人员家庭信息 CRUD插件
 * @Description:
 * @Copyright: FFCS（C） 2017
 * @Company: FFCS
 * @author Wang Yiren
 * @Version 0.0.1 date:2017年11月27日
 * @since JDK1.6
 */
@Controller
@Scope("prototype")
public class UecOutStaffFamilyListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -5811398149406451671L;
	/**
	 * 人员基本信息功能 查询出的实体对象
	 */
	private UecOutStaffInfo uecOutStaffInfo;
	/**
	 * 对应页面上的bean
	 */
	@Getter
	private UecOutStaffFamilyListboxBean bean = new UecOutStaffFamilyListboxBean();
	/**
	 * 人员语言能力实体
	 */
	private UecFamily uecFamily;
	/**
	 * 翻页查询条件实体
	 */
	private UecFamily familyPaging;

	private UecFamily approvalFamilyPaging;

	private List<UecFamily> uecFamilies = new ArrayList<UecFamily>();

	private boolean isOutStaffEntryExt = false;
	/**
	 * 人员语言能力查询实体
	 */
	// private UecFamily qryUecFamily;

	private UecFamilyManager uecFamilyManager = (UecFamilyManager) ApplicationContextUtil
			.getBean("uecFamilyManager");

	private UecTrialManager uecTrialManager = (UecTrialManager) ApplicationContextUtil
			.getBean("uecTrialManager");

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public UecOutStaffFamilyListboxExt() {
		Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_STAFF_FAMILY_EXT_LISTBOX_ZUL,
				this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

		this.addForward(UecOutStaffConstants.ON_UEC_OUT_STAFF_FAMILY_QUERY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_FAMILY_QUERY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_FAMILY_QUERY_OF_OUTSTAFF_ENTRY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_FAMILY_QUERY_OF_OUTSTAFF_ENTRY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_FAMILY_QUERY_OF_OUTSTAFF_ENTRY_VIEW,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_FAMILY_QUERY_OF_OUTSTAFF_ENTRY_VIEW_RESPONSE);

		this.addForward(UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_FAMILY,
				this,
				UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_FAMILY_RESPONSE);

	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 选择查询记录
	 * 
	 * @throws Exception
	 */
	public void onSelectUecFamilyList() throws Exception {
		if (this.bean.getUecFamilyListbox().getSelectedCount() > 0) {
			uecFamily = (UecFamily) bean.getUecFamilyListbox()
					.getSelectedItem().getValue();
		}
	}

	/**
	 * 人员基本信息功能，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutStaffFamilyQueryResponse(ForwardEvent event) {
		uecOutStaffInfo = (UecOutStaffInfo) event.getOrigin().getData();
		if (null != uecOutStaffInfo) {
	        //设置操作按钮，非盟市主管不可操作按钮
	        if(PermissionUtil.isNoMainOutStaff()) {
	            this.setButtonValid(false, true, true, true);
	        }else {
	            this.setButtonValid(true, true, true, false);
	        }
			uecFamily = new UecFamily();
			uecFamily.setStaffId(uecOutStaffInfo.getOutStaffId());
			uecFamily.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
			familyPaging = uecFamily;
			this.onQueryUecFamily();
		}
	}

	/**
	 * 人员基本信息功能，抛出事件， 事件监听，来自入职申请页面
	 * 
	 * @param event
	 */
	public void onUecOutStaffFamilyQueryOfOutStaffEntryResponse(
			ForwardEvent event) {
		uecFamily = null;
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) event.getOrigin()
				.getData();
		if (null != map) {
			isOutStaffEntryExt = (Boolean) map.get("isOutStaffEntryExt");
			uecOutStaffInfo = (UecOutStaffInfo) map.get("uecOutStaffInfo");
			if (null != uecOutStaffInfo) {
				this.setButtonValid(true, true, true, false);
				ListModel list = new BindingListModelList(uecFamilies, true);
				this.bean.getUecFamilyListbox().setModel(list);
				this.bean.getUecFamilyListboxPaging().setTotalSize(1);
			}
		}

	}

	/**
	 * 人员家庭申请审批id，抛出事件，事件监听 审批数据查看
	 * 
	 * @param event
	 */
	public void onUecOutStaffFamilyQueryOfOutStaffEntryViewResponse(
			ForwardEvent event) {
		uecFamilies.clear();
		approvalFamilyPaging = new UecFamily();
		String familyIds = (String) event.getOrigin().getData();
		if (!StrUtil.isNullOrEmpty(familyIds)) {
			String[] familyIdArray = familyIds.split("-");
			if (!StrUtil.isNullOrEmpty(familyIdArray)
					&& familyIdArray.length > 0) {
				for (String familyId : familyIdArray) {
					UecFamily uecFamily = UecFamily.newInstance();
					uecFamily.setFamilyId(Long.parseLong(familyId));
					uecFamily = uecFamilyManager.queryUecFamilyById(uecFamily);
					uecFamilies.add(uecFamily);
				}

				onQueryUecFamily();
			}
		}
	}

	public void onCleanUecOutStaffFamilyResponse(ForwardEvent event) {
		clearVariable();
		uecOutStaffInfo = null;
		ListboxUtils.clearListbox(this.bean.getUecFamilyListbox());
		this.bean.getUecFamilyListboxPaging().setTotalSize(1);
		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 设置按钮
	 * 
	 * @param canAdd
	 * @param candel
	 */
	private void setButtonValid(boolean canView, boolean canAdd,
			boolean canEdit, boolean candel) {
		this.bean.getViewButton().setDisabled(!canView);
		this.bean.getAddButton().setDisabled(!canAdd);
		this.bean.getEditButton().setDisabled(!canEdit);
		this.bean.getDelButton().setDisabled(!candel);
	}

	/**
	 * 查询按钮
	 */
	public void onQueryUecFamily() {
		this.bean.getUecFamilyListboxPaging().setActivePage(0);
		this.onQueryUecFamilyList();
	}

	/**
	 * 重置按钮
	 */
	public void onResetUecFamily() {
		ListboxUtils.clearListbox(this.bean.getUecFamilyListbox());
		this.bean.getUecFamilyListboxPaging().setTotalSize(1);
	}

	/**
	 * 查看按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onViewUecFamily() throws Exception, InterruptedException {
		if (uecFamily != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "view");
			map.put("uecFamily", uecFamily);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_FAMILY_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						//
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要查看的记录", "提示信息");
			return;
		}
	}

	/**
	 * 新增按钮
	 * 
	 * @throws Exception
	 * @throws
	 */
	public void onAddUecFamily() throws Exception {
		if (null != uecOutStaffInfo) {
			if (!isOutStaffEntryExt) {
				boolean isOnTrial = isOnTrial();
				if (!isOnTrial) {
					return;
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "add");
			map.put("uecOutStaffInfo", uecOutStaffInfo);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_FAMILY_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						// 新增或修改完成后，列表从数据库更新
						uecFamily = (UecFamily) event.getData();
						uecFamilies.add(uecFamily);
						if (!isOutStaffEntryExt) {
							onQueryUecFamilyList();
						} else {
							ListModel list = new BindingListModelList(
									uecFamilies, true);
							bean.getUecFamilyListbox().setModel(list);
							bean.getUecFamilyListboxPaging().setTotalSize(1);

							postUecFamily();
						}

					}
				}
			});
		}
	}

	private void postUecFamily() {
		Events.postEvent("onPostFamilyListOfOutStaffEntry", this, uecFamilies);
	}

	/**
	 * 编辑按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onEditUecFamily() throws Exception, InterruptedException {
		if (null != uecFamily) {
			// boolean isOnTrial = isOnTrial();
			// if (!isOnTrial) {
			// return;
			// }
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "edit");
			map.put("uecFamily", uecFamily);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_FAMILY_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						if (isOutStaffEntryExt) {
							uecFamilies.remove(uecFamily);
						}
						uecFamily = (UecFamily) event.getData();
						// 新增或修改完成后，列表从数据库更新
						if (!isOutStaffEntryExt) {
							onQueryUecFamilyList();
						} else {
							uecFamilies.add(uecFamily);
							ListModel list = new BindingListModelList(
									uecFamilies, true);
							bean.getUecFamilyListbox().setModel(list);
							bean.getUecFamilyListboxPaging().setTotalSize(1);

							postUecFamily();
						}

					}
				}
			});
		} else {
			ZkUtil.showError("请选中要编辑的记录", "提示信息");
			return;
		}
	}

	/**
	 * 审批状态中修改
	 * 
	 * @throws SuspendNotAllowedException
	 * @throws InterruptedException
	 */
	public void onApprovalEditUecFamily() throws SuspendNotAllowedException,
			InterruptedException {
		if (null != uecFamily && uecFamily.getId() != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "approvalEdit");
			map.put("uecFamily", uecFamily);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_FAMILY_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						// 新增或修改完成后，列表从数据库更新
						PageInfo pageInfo = uecFamilyManager
								.queryPageInfoByUecFamilyOnApproval(uecFamily,
										bean.getUecFamilyListboxPaging()
												.getActivePage() + 1, bean
												.getUecFamilyListboxPaging()
												.getPageSize());
						ListModel list = new BindingListModelList(pageInfo
								.getDataList(), true);
						bean.getUecFamilyListbox().setModel(list);
						bean.getUecFamilyListboxPaging().setTotalSize(1);
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要修改的记录", "提示信息");
			return;
		}
	}

	/**
	 * 删除按钮
	 */
	public void onDelUecFamily() {
		if (this.uecFamily != null && uecFamily.getId() != null) {
			ZkUtil.showQuestion("确定要删除吗?", "提示信息", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Integer result = (Integer) event.getData();
					if (result == Messagebox.OK) {
						uecFamily.removeOnly();
						PubUtil.reDisplayListbox(bean.getUecFamilyListbox(),
								uecFamily, "del");
						uecFamily = null;
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要删除的记录", "提示信息");
			return;
		}
	}

	/**
	 * 翻页
	 */
	public void onUecOutFamilyListboxPaging() {
		this.onQueryUecFamilyList();
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecFamily = null;
		familyPaging = null;
		uecFamilies.clear();
	}

	/**
	 * 查询
	 */
	public void onQueryUecFamilyList() {
		// 翻页查看生效数据
		if (null != familyPaging) {
			PageInfo pageInfo = uecFamilyManager.queryPageInfoByUecFamily(
					familyPaging, this.bean.getUecFamilyListboxPaging()
							.getActivePage() + 1, this.bean
							.getUecFamilyListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(pageInfo.getDataList(),
					true);
			this.bean.getUecFamilyListbox().setModel(list);
			this.bean.getUecFamilyListboxPaging().setTotalSize(
					pageInfo.getTotalCount());
			// 入职 页添加记录后，不选择记录时不弹出弹窗
			uecFamily = null;
		}
		// 翻页 查看审批数据
		if (null != approvalFamilyPaging) {
//			List<UecFamily> pageFamilies = getCurrentPageList(uecFamilies, bean
//					.getUecFamilyListboxPaging().getActivePage() + 1, bean
//					.getUecFamilyListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(uecFamilies, true);
			this.bean.getUecFamilyListbox().setModel(list);
			this.bean.getUecFamilyListboxPaging().setTotalSize(1);
			uecFamily = null;
		}
	}

	/**
	 * 获取当前页list
	 * 
	 * @param list
	 * @param activePage
	 * @param pageSize
	 * @return
	 */
	public List<UecFamily> getCurrentPageList(List<UecFamily> list, int activePage,
			int pageSize) {
		int fromIndex = activePage * pageSize;
		int toIndex = fromIndex + pageSize;
		if (fromIndex >= list.size()) {
			return null;
		}
		if (toIndex >= list.size()) {
			return list.subList(fromIndex, list.size());
		}
		return list.subList(fromIndex, toIndex);

	}

	/**
	 * 判断是否入职
	 * 
	 * @return
	 */
	private boolean isOnTrial() {
		UecTrial qryUecTrial = UecTrial.newInstance();
		qryUecTrial.setStaffId(uecOutStaffInfo.getOutStaffId());
		qryUecTrial.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		qryUecTrial = uecTrialManager.findUecTrial(qryUecTrial);
		if (null == qryUecTrial) {
			ZkUtil.showError("此人未入职,请先执行入职操作", "温馨提示");
			return false;
		}
		return true;
	}

}
